<template>
  <div v-if="isShow">
    <!-- 物流 -->
    <logistic
      :way="routerVal.way"
      :address="userAddress"
      v-if="currentDistribution === 'LOGISTICS' && goodsType !== 'VIRTUAL_GOODS'" />
    <pickup :way="routerVal.way" :address="storeAddress" v-if="currentDistribution === 'SELF_PICK_UP'" />

    <div card>
      <groupBuy v-if="routerVal.way === 'PINTUAN'" />
    </div>
    <div card>
      <!-- 商品 -->
      <div p-32rpx my-20rpx v-for="(item, index) in orderInfo.cartList" :key="index">
        <div
          @click="$navigateTo('/pages/goods/store/detail?id=' + item.storeId)"
          mb-30rpx
          text-28rpx
          font-bold
          flex
          flex-a-c>
          {{ item.storeName }}
          <nut-icon size="12" name="rect-right"></nut-icon>
        </div>
        <div class="promotionNotice">{{ item.promotionNotice || '' }}</div>
        <div
          @click.native="
            $navigateTo('/pages/goods/product/detail?skuId=' + sku.goodsSku.id + '&goodsId=' + sku.goodsSku.goodsId)
          "
          v-for="(sku, skuIndex) in item.skuList"
          :key="skuIndex"
          mb-20rpx>
          <column :isOrder="true" :price="sku.purchasePrice" :image="sku.goodsSku.thumbnail" :res="sku"></column>
        </div>
        <div class="order-cell px-0">
          <div class="order-cell_label">备注信息：</div>
          <div class="order-cell_value">
            <input
              class="note"
              placeholder="请输入内容"
              :border="false"
              style="text-align: right"
              :input-style="inputStyle"
              v-model="remarkVal[index].remark" />
          </div>
        </div>
      </div>
      <!-- 发票、备注信息 -->
      <div mb-20rpx>
        <div class="order-cell">
          <div class="order-cell_label">发票信息：</div>
          <div class="order-cell_value" @click.native="invoicesRef.show = true">
            <span v-if="receiptList">{{ receiptList.receiptTitle }} - {{ receiptList.receiptContent }}</span>
            <span v-else>不开发票</span>
          </div>
        </div>
        <div class="order-cell" v-if="goodsType !== 'VIRTUAL_GOODS'">
          <div class="order-cell_label">配送：</div>
          <div class="order-cell_value" @click="chooseDisMethods()">
            {{
              distributionList.find((e: any) => {
                return e.value === currentDistribution
              })?.label
            }}
          </div>
        </div>
      </div>
    </div>
    <!-- 商品优惠信息 -->
    <div card>
      <div class="order-cell">
        <div class="order-cell_label" v-if="orderInfo.priceDetailDTO">商品合计：</div>
        <div class="order-cell_value text-main-color text-30rpx">
          {{ unitPrice(orderInfo.priceDetailDTO?.goodsPrice, '￥') }}
        </div>
      </div>

      <div class="order-cell" v-if="currentDistribution === 'LOGISTICS'">
        <div class="order-cell_label">运费：</div>
        <div class="order-cell_value">
          <span v-if="orderInfo.priceDetailDTO?.freightPrice === 0">包邮</span>
          <span v-else>
            {{ unitPrice(orderInfo.priceDetailDTO?.freightPrice, '￥') }}
          </span>
        </div>
      </div>
      <div class="order-cell">
        <div class="order-cell_label">优惠券：</div>
        <div class="order-cell_value" @click="pickTheCoupon">
          <span text-main-color v-if="orderInfo.priceDetailDTO?.couponPrice">
            -{{ unitPrice(orderInfo.priceDetailDTO?.couponPrice, '￥') }}
          </span>
          <span v-else>{{ orderInfo?.canUseCoupons ? orderInfo?.canUseCoupons.length : '0' }} 张可用</span>
        </div>
      </div>
      <div class="order-cell">
        <div class="order-cell_label">优惠金额：</div>
        <div class="order-cell_value">
          <span text-main-color v-if="orderInfo.priceDetailDTO && orderInfo.priceDetailDTO?.couponPrice">
            -{{ unitPrice(orderInfo.priceDetailDTO?.couponPrice, '￥') }}
          </span>
          <span v-else>0.00</span>
        </div>
      </div>
      <div class="order-cell">
        <div class="order-cell_label">活动优惠：</div>
        <div class="order-cell_value">
          <span v-if="orderInfo.priceDetailDTO?.discountPrice">
            -{{ unitPrice(orderInfo.priceDetailDTO.discountPrice, '￥') }}
          </span>
          <span v-else>0.00</span>
        </div>
      </div>
    </div>

    <div pb-300rpx></div>
    <div position-fixed bottom-100rpx w-full style="bottom: calc(100rpx + env(safe-area-inset-bottom));">
      <nut-noticebar
        v-if="notSupportFreight.length != 0"
        w-full
        :text="notSupportFreightGoodsList.join(',')"
        :background="colors.tooLightColor"
        :custom-color="colors.themeColor"></nut-noticebar>
    </div>
    <div bg-white w-full class="tabbar safe-bottom"  position-fixed bottom-0 h-100rpx flex flex-a-c flex-j-sb>
      <div pl-32rpx  text-main-color font-bold text-38rpx>
        <!-- 积分商品展示积分 -->
        <span v-if="orderInfo.cartTypeEnum === 'POINTS'">
          {{ unitPrice(orderInfo.priceDetailDTO?.flowPrice || 0, '￥') }} +
          {{ orderInfo.priceDetailDTO?.payPoint || 0 }}
          <span text-24rpx>积分</span>
        </span>
        <!-- <span v-if="orderInfo.promotionType === 'POINTS_GOODS'">
          {{ unitPrice(orderInfo.priceDetailDTO?.flowPrice || 0, '￥') }} +
          {{ orderInfo.priceDetailDTO?.payPoint || 0 }}
          <span text-24rpx>积分</span>
        </span> -->
        <span v-else>
          {{ unitPrice(orderInfo.priceDetailDTO?.flowPrice || 0, '￥') }}
        </span>
      </div>

      <div pr-32rpx   @click="billOrder">
        <!-- #ifndef MP-WEIXIN -->
        <nut-button type="primary" :loading="loading">提交订单</nut-button>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <nut-button type="primary" :loading="loading">支付</nut-button>
        <!-- #endif -->
      </div>
    </div>

    <nut-popup v-model:visible="showChooseDir" position="bottom" safe-area-inset-bottom>
      <nut-picker
        :swipe-duration="500"
        :field-names="{ text: 'label', value: 'value' }"
        :columns="distributionList"
        title="选择配送方式"
        @confirm="shoosenDir"
        @cancel="showChooseDir = false"></nut-picker>
    </nut-popup>

    <invoices ref="invoicesRef" :res="receiptList" @callbackInvoice="callbackInvoice"></invoices>
  </div>
</template>

<script setup lang="ts">
import { getDefaultAddress } from '@/api/address'
import { getReceipt } from '@/api/order'
import { createTrade, getCanUseDistribution, getCheckoutParams, toggleShipMethod } from '@/api/trade'
import column from '@/components/goods-list/column.vue'
import invoices from '@/components/invoices/index.vue'
import { colors, InputStyle } from '@/constants/injection-key'
import LiLiWXPay from '@/js_sdk/lili-pay/wx-pay'
import groupBuy from '@/pages/mine/order/template/group.vue'
import logistic from '@/pages/mine/order/template/logistic.vue'
import pickup from '@/pages/mine/order/template/pickup.vue'
import { unitPrice } from '@/utils/filters'
import storage from '@/utils/storage'
import { onBackPress, onLoad, onShow } from '@dcloudio/uni-app'
const inputStyle = { ...InputStyle, textAlign: 'right' }
const isShow = ref<any>(false)
const userAddress = ref<any>('') //用户默认地址
const goodsType = ref<any>('') //商品类型
const orderInfo = ref<any>('') //用户信息
const routerVal = ref<any>('') //路径传参
const loading = ref<boolean>(false)
const remarkVal = ref<any>([])
const showChooseDir = ref<boolean>(false) // 选择配送方式
const isRemark = ref<boolean>(false) // 是否有备注
const currentDistribution = ref<'LOGISTICS' | 'SELF_PICK_UP'>('LOGISTICS')
const distributionList = ref<any>([
  {
    value: 'LOGISTICS',
    label: '物流'
  },
  {
    value: 'SELF_PICK_UP',
    label: '自提'
  }
])
const notSupportFreight = ref([]) //不支持运费
const notSupportFreightGoodsList = ref(['以下商品超出配送范围：'])
const storeAddress = ref<any>('')
const invoicesRef = ref<any>() // 发票组件
const receiptList = ref<any>() // 发票信息

// 发票回调，选择发票后刷新购物车
async function callbackInvoice(val: any) {
  invoicesRef.value.show = false
  receiptList.value = val
  if (val) {
    let submit = { way: routerVal.value.way, ...receiptList.value }
    let receipt = await getReceipt(submit)
    if (receipt.data.success) {
      fetchOrderDetail()
    }
  }
}

onShow(() => {
  getDistribution()
  fetchOrderDetail()
})

async function shoosenDir(params: any) {
  const dir = params.selectedValue[0]
  let res = await toggleShipMethod({
    shippingMethod: dir,
    way: routerVal.value.way
  })
  currentDistribution.value = dir
  showChooseDir.value = false
  if (res.data.success) {
    fetchOrderDetail()
  }
}

function chooseDisMethods() {
  showChooseDir.value = true
}

// 选择优惠券
function pickTheCoupon() {
  const canUseCoupon = orderInfo.value?.canUseCoupons
  storage.setCanUseCoupon(canUseCoupon)

  let selectedCoupon = []
  if (orderInfo.value.platformCoupon) selectedCoupon.push(orderInfo.value.platformCoupon.memberCoupon.id)
  if (orderInfo.value.storeCoupons && Object.keys(orderInfo.value.storeCoupons)) {
    for (let key in Object.keys(orderInfo.value.storeCoupons)) {
      console.log('key', key)
      let storeMemberCouponsId = Object.keys(orderInfo.value.storeCoupons)[key]
      console.log('storeMemberCouponsId', storeMemberCouponsId)
      console.log(
        'orderInfo.value.storeCoupons[storeMemberCouponsId]',
        orderInfo.value.storeCoupons[storeMemberCouponsId]
      )
      // return
      let storeCouponId = orderInfo.value.storeCoupons[key].memberCouponDTO.memberCoupon.id
      selectedCoupon.push(storeCouponId)
    }
  }
  uni.navigateTo({
    url: `/pages/mine/coupon/pick?way=${routerVal.value.way}&selectedCoupon=${selectedCoupon}`
  })
}

// 验证通过返回true
function verify() {
  let flag = true
  if (currentDistribution.value === 'LOGISTICS' && goodsType.value !== 'VIRTUAL_GOODS') {
    if (!userAddress.value.id) {
      uni.showToast({
        title: '请选择地址',
        duration: 2000,
        icon: 'none'
      })
      return flag
    }
    return flag
  } else if (currentDistribution.value === 'SELF_PICK_UP') {
    if (!storeAddress.value.id) {
      uni.showToast({
        title: '请选择提货点',
        duration: 2000,
        icon: 'none'
      })
      return flag
    }
    return flag
  } else if (goodsType.value === 'VIRTUAL_GOODS') {
    return flag
  }
  // VIRTUAL_GOODS
}

// 创建订单
function createOrder() {
  let client
  // #ifdef H5
  client = 'H5'
  // #endif
  // #ifdef MP-WEIXIN
  client = 'WECHAT_MP'
  // #endif
  // #ifdef APP-PLUS
  client = 'APP'
  // #endif

  // 提交submit
  let submit: {
    client: string
    way: string
    remark: any
    parentOrderSn?: string
  } = {
    client,
    way: routerVal.value.way,
    remark: remarkVal.value,
    parentOrderSn: ''
  }
  // 如果是拼团并且当前用户不是团长
  if (routerVal.value.parentOrderSn) {
    submit.parentOrderSn = routerVal.value.parentOrderSn
    console.log('是不是突然长', submit.parentOrderSn)
  } else {
    delete submit.parentOrderSn
  }

  return submit
}

// 结算账单
async function billOrder() {
  loading.value = true
  if (verify()) {
    //  创建订单
    const submit = createOrder()
    try {
      const res = await createTrade(submit)
      if (res.data.success) {
        // 如果金额为0跳转到订单详情
        if (orderInfo.value.priceDetailDTO.billPrice === 0) {
          uni.redirectTo({
            url: '/pages/mine/order/list'
          })
        } else {
          // #TODO 4.26 先用余额支付
          uni.redirectTo({
            url: `/pages/mine/payment/payOrder?trade_sn=${res.data.result.sn}`
          })

          // // 如果不为0跳转到支付
          // // #ifndef MP-WEIXIN
          // uni.navigateTo({
          //   url: `/pages/mine/payment/payOrder?trade_sn=${res.data.result.sn}`
          // });
          // // #endif

          // // 如果当前是微信小程序 直接开启微信支付
          // // #ifdef MP-WEIXIN
          // // 微信小程序中点击创建订单直接开始支付
          // pay(res.data.result.sn);
          // // #endif
        }
      } else {
        loading.value = false
      }
    } catch (error) {
      loading.value = false
    }
  } else {
    loading.value = false
  }
}

async function pay(sn: string) {
  new LiLiWXPay({
    sn: sn,
    price: orderInfo.value.priceDetailDTO.billPrice
  }).pay()
}

// 获取用户地址
async function fetchUserAddress() {
  const res = await getDefaultAddress()
  if (res.data.result) {
    res.data.result.consigneeAddressPath = res.data.result.consigneeAddressPath.split(',')
    userAddress.value = res.data.result
  }
}

// 获取配送列表
async function getDistribution() {
  const res = await getCanUseDistribution({ way: routerVal.value.way })
  if (res.data.success) {
    let way: any = []
    distributionList.value.forEach((item: any) => {
      res.data.result.forEach((child: any) => {
        if (item.value == child) {
          way.push(item)
        }
      })
    })
    distributionList.value = way
  }
}

// 获取订单
async function fetchOrderDetail() {
  notSupportFreight.value = []
  const res = await getCheckoutParams(routerVal.value.way)
  isShow.value = true
  if (res.data.success) {
    orderInfo.value = res.data.result
    if (res.data.result.cartList[0] && res.data.result.cartList[0].checkedSkuList[0]) {
      goodsType.value = res.data.result.cartList[0].checkedSkuList[0].goodsSku.goodsType
    }
    storeAddress.value = {
      ...res.data.result.storeAddress,
      storeId: res.data.result.cartList[0].storeId
    }

    // 根据购物车list 来赋值备注
    res.data.result.cartList.forEach((item: any, index: number) => {
      // 如果已经写过备注信息的话赋值
      let repeatData: any = {
        remark: isRemark.value
          ? remarkVal.value[index].storeId === item.storeId
            ? remarkVal.value[index].remark
            : item.remark
          : item.remark,
        storeId: item.storeId
      }
      remarkVal.value[index] = repeatData
    })

    if (res.data.result.notSupportFreight && res.data.result.notSupportFreight.length !== 0) {
      notSupportFreight.value = res.data.result.notSupportFreight

      res.data.result.notSupportFreight.forEach((item: any) => {
        notSupportFreightGoodsList.value[0] += item.goodsSku.goodsName
      })
    }

    if (!res.data.result.memberAddress) {
      fetchUserAddress()
    } else {
      userAddress.value = res.data.result.memberAddress
      res.data.result.memberAddress.consigneeAddressPath = res.data.result.memberAddress.consigneeAddressPath.split(',')
    }
  }
}
onLoad((options) => {
  routerVal.value = options
})

onBackPress(() => {})
</script>
<style scoped lang="scss">
.tabbar {
  border-top: 1px solid #ededed;
}

.text-30rpx {
  font-size: 30rpx !important;
}

.order-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  font-size: 24rpx;

  &_label {
    color: #666;
    font-size: 24rpx;
    min-width: 150rpx;
  }

  &_value {
    font-weight: bold;
    text-align: right;
    font-size: 26rpx;
  }
}

.px-0 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.promotionNotice {
  font-size: 24rpx;
  margin: 20rpx 0;
  color: #ff9f28;
}
</style>
